package com.java.common.config;

import com.java.common.exception.RRException;
import com.java.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @author jl
 * Created on 2020/10/6
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(RRException.class)
    public R handleRRException(RRException e) {
        log.error("业务异常:{}", e.getMessage());
        R r = new R();
        r.put("status",500);
        r.put("msg", e.getMessage());
        r.put("success", false);
        return r;
    }

    /**
     * 处理参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleBindException(MethodArgumentNotValidException e) {
        log.error(e.getMessage());
        List<ObjectError> errors = e.getBindingResult().getAllErrors();
        ObjectError error = errors.get(0);
        String msg = error.getDefaultMessage();
        R r = new R();
        r.put("status",500);
        r.put("msg", msg);
        r.put("success", false);
        return r;
    }

    @ExceptionHandler(Exception.class)
    public R handleException(Exception e) {
        log.error(e.getMessage(), e);
        return R.error();
    }
}
